﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Base;
using Lamex.Interface;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Columns;

namespace Lamex.mIE.UI
{
    public partial class frmIE_Plus_Memu_Structure : frmBaseChild
    //public partial class frmIE_Plus_Memu_Structure : Form
    {
        DataTable dt;
        string strSql;

        DataTable dt3, dt2, dt1;
        int iCount3, iCount2, iCount1;

        string strOld_Menu, strNew_Menu;
        TreeNode tnLast1, tnLast2;

        public frmIE_Plus_Memu_Structure()
        {
            InitializeComponent();
        }

        private void frmIE_Plus_Memu_Structure_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            //单元格合并，合并单元格
            gridView1.OptionsView.AllowCellMerge = true;
            gridView2.OptionsView.AllowCellMerge = true;

            getSearchLookUpEditValue();

            //setTreeListData();

            //treeView1.Nodes.Clear();
            treeView1.Nodes.Add("IE+菜单（旧版）");
            addTreeViewRootNode_TreeView1(treeView1);//添加根节点
            addTreeViewSubNode_TreeView1(treeView1);//添加子节点
            treeView1.ExpandAll();

            //treeView2.Nodes.Clear();
            treeView2.Nodes.Add("IE+菜单（新版）");
            addTreeViewRootNode_TreeView2(treeView2);//添加根节点
            addTreeViewSubNode_TreeView2(treeView2);//添加子节点
            addTreeViewSubSubNode_TreeView2(treeView2);//添加子子节点
            treeView2.ExpandAll();

            refreshDataToUI();
        }

        private void frmIE_Plus_Memu_Structure_Resize(object sender, EventArgs e)
        {
            //splitContainerControl1.SplitterPosition = this.Width / 2;
            //splitContainerControl2.SplitterPosition = this.Width / 4;
            //splitContainerControl3.SplitterPosition = this.Width / 4;

            splitContainerControl1.SplitterPosition = 0;
            splitContainerControl2.SplitterPosition = 0;
            splitContainerControl3.SplitterPosition = this.Width / 2;
        }

        private void sbtnView_Click(object sender, EventArgs e)
        {
            refreshDataToUI();
        }

        private void refreshDataToUI()
        {
            gridControl1.DataSource = null;
            gridControl1.DataSource = null;

            gridView1.Columns.Clear();
            gridView2.Columns.Clear();

            strSql = @"SELECT V0_LEVEL_1 AS 旧版Ⅰ级,V0_LEVEL_2 AS 旧版Ⅱ级,V0_LEVEL_3 AS 旧版Ⅲ级
FROM IE_Plus_Menu_Stucture";

            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            gridControl1.DataSource = dt;

            strSql = @"SELECT V1_LEVEL_1 AS 新版Ⅰ级,V1_LEVEL_2 AS 新版Ⅱ级,V1_LEVEL_3 AS 新版Ⅲ级
FROM IE_Plus_Menu_Stucture";

            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            gridControl2.DataSource = dt;

            treeView1.SelectedNode = treeView1.Nodes[0];
            treeView2.SelectedNode = treeView2.Nodes[0];
        }

        private void searchLookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {
            strOld_Menu = searchLookUpEdit1.Text;

            strSql = @"SELECT V1_LEVEL_1 + ' -> ' + V1_LEVEL_2 + ' -> ' + V1_LEVEL_3 AS Menu_Name,
count(V1_LEVEL_3) AS Menu_Count,V1_LEVEL_3 AS Fun_Name 
FROM IE_Plus_Menu_Stucture
WHERE V1_LEVEL_3='" + strOld_Menu + @"'
GROUP BY V1_LEVEL_1,V1_LEVEL_2,V1_LEVEL_3";
            dt3 = BaseBuildSql.GetDataTableBySql(strSql);
            if (dt3.Rows.Count > 0) iCount3 = int.Parse(dt3.Rows[0][1].ToString());

            strSql = @"SELECT V1_LEVEL_1 + ' -> ' + V1_LEVEL_2 AS Menu_Name,
count(V1_LEVEL_2) AS Menu_Count2,V1_LEVEL_2 AS Fun_Name  
FROM IE_Plus_Menu_Stucture
WHERE V1_LEVEL_2='" + strOld_Menu + @"'
GROUP BY V1_LEVEL_1,V1_LEVEL_2";
            dt2 = BaseBuildSql.GetDataTableBySql(strSql);
            if (dt2.Rows.Count > 0) iCount2 = int.Parse(dt2.Rows[0][1].ToString());

            strSql = @"SELECT V1_LEVEL_1 AS Menu_Name,
count(V1_LEVEL_1) AS Menu_Count1,V1_LEVEL_1 AS Fun_Name  
FROM IE_Plus_Menu_Stucture
WHERE V1_LEVEL_1='" + strOld_Menu + @"'
GROUP BY V1_LEVEL_1";
            dt1 = BaseBuildSql.GetDataTableBySql(strSql);
            if (dt1.Rows.Count > 0) iCount1 = int.Parse(dt1.Rows[0][1].ToString());

            if (iCount3 == 1)
            {
                textEdit1.Text = dt3.Rows[0][0].ToString();
                strNew_Menu = dt3.Rows[0][2].ToString();
            }
            else if (iCount2 == 1)
            {
                textEdit1.Text = dt2.Rows[0][0].ToString();
                strNew_Menu = dt2.Rows[0][2].ToString();
            }
            else if (iCount1 == 1)
            {
                textEdit1.Text = dt1.Rows[0][0].ToString();
                strNew_Menu = dt1.Rows[0][2].ToString();
            }

            doGridViewLocation();
            doTreeViewLocation();
        }

        //同步定位TreeView节点
        private void doGridViewLocation()
        {
            //暂不开发
        }

        //同步定位TreeView节点
        private void doTreeViewLocation()
        {
            ResetAllNodesBackColor(treeView1.Nodes[0]);
            //treeView1.SelectedNode = treeView1.Nodes.Find(strNew_Menu, true)[0];//无效
            tnLast1 = FindNodeByText(treeView1.Nodes[0], strNew_Menu);
            treeView1.SelectedNode = tnLast1;
            treeView1.SelectedNode.BackColor = Color.LawnGreen;//草绿色
            treeView1.SelectedNode.Parent.BackColor = Color.LawnGreen;//草绿色

            ResetAllNodesBackColor(treeView2.Nodes[0]);
            tnLast2 = FindNodeByText(treeView2.Nodes[0], strNew_Menu);
            treeView2.SelectedNode = tnLast2;
            treeView2.SelectedNode.BackColor = Color.LawnGreen;//草绿色
            treeView2.SelectedNode.Parent.BackColor = Color.LawnGreen;//草绿色
        }

        //重置所有节点背景色
        private TreeNode ResetAllNodesBackColor(TreeNode tnParent)
        {
            if (tnParent == null) return null;
            TreeNode tnRet = null;

            foreach (TreeNode tn in tnParent.Nodes)
            {
                tn.BackColor = Color.White;
                tnRet = ResetAllNodesBackColor(tn);
                if (tnRet != null) break;
            }
            return tnRet;
        }

        /// <summary>
        /// 获取 指定Text值的节点
        /// </summary>
        /// <param name="tnParent">指定节点</param>
        /// <param name="strValue">Text值</param>
        /// <returns></returns>
        private TreeNode FindNodeByText(TreeNode tnParent, string strText)
        {
            if (tnParent == null) return null;
            if (tnParent.Text == strText) return tnParent;
            TreeNode tnRet = null;

            foreach (TreeNode tn in tnParent.Nodes)
            {
                tnRet = FindNodeByText(tn, strText);
                if (tnRet != null) break;
            }
            return tnRet;
        }

        public void getSearchLookUpEditValue()
        {
            strSql = @"SELECT V0_LEVEL_1 AS 一级菜单,V0_LEVEL_2 AS 二级菜单,
CASE WHEN V0_LEVEL_2 IS NULL THEN V0_LEVEL_1 ELSE V0_LEVEL_2 END
AS 菜单名称
FROM IE_Plus_Menu_Stucture
WHERE DISNABLED IS NULL ";

            dt = BaseBuildSql.GetDataTableBySql(strSql);

            searchLookUpEdit1.Properties.ValueMember = "菜单名称";
            searchLookUpEdit1.Properties.DisplayMember = "菜单名称";
            searchLookUpEdit1.Properties.DataSource = dt;
            searchLookUpEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            searchLookUpEdit1.Properties.ImmediatePopup = true;
            searchLookUpEdit1.Properties.NullText = "选择菜单项目";
        }

        public void setTreeListData()
        {
            strSql = @"SELECT V0_LEVEL_1 AS 一级菜单,V0_LEVEL_2 AS 二级菜单,V0_LEVEL_3 AS 三级菜单
FROM IE_Plus_Menu_Stucture";

            dt = BaseBuildSql.GetDataTableBySql(strSql);

            treeList1.KeyFieldName = "OID";//主键名称
            treeList1.ParentFieldName = "ParentOID";//父级ID
            treeList1.DataSource = dt;//数据源
            treeList1.ExpandAll();//全部展开
        }
        
        #region 树形菜单加载

        //样例：https://www.cnblogs.com/net064/p/5534697.html
        //获取所有数据库，并加载treeView1
        private void addTreeViewRootNode_TreeView1(TreeView tr1)
        {
            //因要按数据表设定的顺序加载，所以SQL语句复杂化
            //strSql = @"SELECT DISTINCT V0_LEVEL_1 
            //FROM IE_Plus_Menu_Stucture";

            strSql = @"SELECT DISTINCT ORDER_NO,a.V0_LEVEL_1
FROM
(SELECT DISTINCT V0_LEVEL_1
FROM IE_Plus_Menu_Stucture) AS a
LEFT JOIN 
(SELECT V0_LEVEL_1,MIN(ORDER_NO) AS ORDER_NO
FROM IE_Plus_Menu_Stucture
GROUP BY V0_LEVEL_1) AS b
ON a.V0_LEVEL_1=b.V0_LEVEL_1
ORDER BY ORDER_NO";

            dt = BaseBuildSql.GetDataTableBySql(strSql);

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    tr1.Nodes[0].Nodes.Add(dr["V0_LEVEL_1"].ToString());
                }
            }
        }

        private void addTreeViewSubNode_TreeView1(TreeView tr1)
        {
            strSql = @"SELECT DISTINCT V0_LEVEL_1,V0_LEVEL_2 
FROM IE_Plus_Menu_Stucture 
WHERE V0_LEVEL_2 IS NOT NULL AND DISNABLED IS NULL";

            dt = null;
            dt = BaseBuildSql.GetDataTableBySql(strSql);

            if (dt.Rows.Count > 0)
            {
                foreach (TreeNode node in tr1.Nodes)
                {
                    getNodeRecurve(node, dt, "V0_LEVEL_1", "V0_LEVEL_2");
                }
            }
        }

        private void addTreeViewRootNode_TreeView2(TreeView tr1)
        {
            strSql = @"SELECT DISTINCT ORDER_NO,a.V1_LEVEL_1
FROM
(SELECT DISTINCT V1_LEVEL_1
FROM IE_Plus_Menu_Stucture) AS a
LEFT JOIN 
(SELECT V1_LEVEL_1,MIN(ORDER_NO) AS ORDER_NO
FROM IE_Plus_Menu_Stucture
GROUP BY V1_LEVEL_1) AS b
ON a.V1_LEVEL_1=b.V1_LEVEL_1
ORDER BY ORDER_NO";

            dt = BaseBuildSql.GetDataTableBySql(strSql);

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    tr1.Nodes[0].Nodes.Add(dr["V1_LEVEL_1"].ToString());
                }
            }
        }

        private void addTreeViewSubNode_TreeView2(TreeView tr1)
        {
            //            strSql = @"SELECT DISTINCT V1_LEVEL_1,V1_LEVEL_2 
            //FROM IE_Plus_Menu_Stucture 
            //WHERE V1_LEVEL_2 IS NOT NULL";

            strSql = @"SELECT DISTINCT ORDER_NO,a.V1_LEVEL_1,a.V1_LEVEL_2
FROM
(SELECT DISTINCT V1_LEVEL_1,V1_LEVEL_2
FROM IE_Plus_Menu_Stucture) AS a
LEFT JOIN 
(SELECT V1_LEVEL_2,MIN(ORDER_NO) AS ORDER_NO
FROM IE_Plus_Menu_Stucture
GROUP BY V1_LEVEL_2) AS b
ON a.V1_LEVEL_2=b.V1_LEVEL_2
ORDER BY ORDER_NO";

            dt = BaseBuildSql.GetDataTableBySql(strSql);

            if (dt.Rows.Count > 0)
            {
                foreach (TreeNode node in tr1.Nodes)
                {
                    getNodeRecurve(node, dt, "V1_LEVEL_1", "V1_LEVEL_2");
                }
            }
        }

        private void addTreeViewSubSubNode_TreeView2(TreeView tr1)
        {
            strSql = @"SELECT DISTINCT V1_LEVEL_2,V1_LEVEL_3 
FROM IE_Plus_Menu_Stucture 
WHERE V1_LEVEL_3 IS NOT NULL AND DISNABLED IS NULL";

            dt = BaseBuildSql.GetDataTableBySql(strSql);

            if (dt.Rows.Count > 0)
            {
                foreach (TreeNode node in tr1.Nodes)
                {
                    getNodeRecurve(node, dt, "V1_LEVEL_2", "V1_LEVEL_3");
                }
            }
        }

        private void getNodeRecurve(TreeNode tn, DataTable dt, string str1, string str2)
        {
            foreach (DataRow dr in dt.Rows)
            {
                if (tn.Text == dr[str1].ToString())
                {
                    tn.Nodes.Add(dr[str2].ToString());
                }
            }

            foreach (TreeNode tnSub in tn.Nodes)
            {
                getNodeRecurve(tnSub, dt, str1, str2);
            }
        }

        #endregion

        private void 显示选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelControl1.Height = 60;
        }

        private void 隐藏查询区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelControl1.Height = 3;
        }

        public override void DoView(IButtonInfo sender)
        {
            refreshDataToUI();
            base.DoView(sender);
        }

        #region 自动焦点定位，暂不开发

        private void gridView1_Click(object sender, EventArgs e)
        {
            int iRow = gridView1.FocusedRowHandle;
            string strMaterial = gridView1.GetRowCellDisplayText(iRow, "Material_No").ToString();
            GetFoucuseRowHandle(strMaterial, gridControl2, gridView2, "MATERIAL_NO");
        }

        private void gridView2_Click(object sender, EventArgs e)
        {
            int iRow = gridView2.FocusedRowHandle;
            string strMaterial = gridView2.GetRowCellDisplayText(iRow, "MATERIAL_NO").ToString();
            //参数1：需点击Gridcontrol行物料号 | 参数2：定位的gridcontrol | 参数3：定位的gridview | 参数4：定位的物料Filename 
            GetFoucuseRowHandle(strMaterial, gridControl1, gridView1, "Material_No");
        }

        //自动定位至焦点行
        public void GetFoucuseRowHandle(string strMaterial, GridControl gc, GridView gv, string topRowName)
        {
            string searchText = strMaterial;
            ColumnView view = (ColumnView)gc.FocusedView;
            GridColumn column = view.Columns[topRowName];//Material_No
            if (column != null)
            {
                // int rhFound = view.LocateByDisplayText(view.FocusedRowHandle, column, searchText);
                int rhFound = gv.LocateByValue(0, gv.Columns[topRowName], searchText);
                if (rhFound != GridControl.InvalidRowHandle)
                {
                    view.FocusedRowHandle = rhFound;
                    view.FocusedColumn = column;
                }
            }
        }

        #endregion
    }
}